<template>
  <div class="app-container">
    <div class="div-sch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="公司名称" prop="deptName">
          <el-input
            v-model="queryParams.deptName"
            placeholder="请输入公司名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="div-t">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:company:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <!-- <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:company:remove']"
          >删除</el-button>-->
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        border
        :data="postList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="公司名称" align="center" prop="deptName" />
        <el-table-column label="公司LOGO"  align="center" prop="deptLogo" width="100">
          <template slot-scope="scope">
            <el-image 
              style="width: 50px; height: 50px"
              :src="setImg(scope.row.deptLogo)" 
              :preview-src-list="[setImg(scope.row.deptLogo)]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="leader" />
        <el-table-column label="手机" align="center" prop="phone" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="自动审核" align="center" prop="deptName">
          <template slot-scope="scope">
            <el-switch
              @change="disableThis($event,scope.row.deptId)"
              v-model="!scope.row.autoCheck"
              active-color="#ff4949"
              inactive-color="#13ce66"
              active-text="禁用"
              inactive-text="启用"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="下载二维码" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDown(scope.row.qrCode)"
              v-hasPermi="['system:company:edit']"
            >下载</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:company:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:company:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <!-- 添加或修改的对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="公司LOGO" prop="deptLogo">
              <img style="width: 130px;height: 145px;" alt :src="form.deptLogo||defaultUploadImg"  @click="uploadImg()" />
              <div style="font-size:15px;color:red">提示：格式支持jpg,jpeg,png</div>
              <input type="file"  ref="imgFile" accept=".png, .jpeg, .jpg" @change="onchangemd" style="display:none;"/>
          </el-form-item>
          <el-form-item label="公司名称" prop="deptName">
            <el-input v-model="form.deptName" placeholder="请输入公司名称" />
          </el-form-item>
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="form.leader" placeholder="请输入负责人" />
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { companyApi } from "@/api/system/company";
import badImg from '@/assets/images/bad_img.jpg';
import { Download } from "@/utils/downLoad";
import defaultUploadImg from '@/assets/images/default_upload.png';

export default {
  name: "white",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      defaultUploadImg,
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "dept_id",
        deptName: undefined
      },
      deptOptions: [
        {
          deptName: "选项一",
          deptId: 1
        },
        {
          deptName: "选项二",
          deptId: 2
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            pattern: /^1(3|4|5|7|8|9)\d{9}$/,
            message: "手机号格式错误",
            trigger: "blur"
          }
        ],
        deptName: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        leader: [
          { required: true, message: "负责人姓名不能为空", trigger: "blur" }
        ],
        email: [
          {
            required: false,
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ]
      },
      download : new Download()
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询 */
    getList() {
      this.loading = true;
      companyApi
        .companyList(this.queryParams)
        .then(response => {
          this.postList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        })
        .catch(err => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        phone: undefined,
        isDelete: undefined,
        remark: undefined,
        deptLogo: null
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection);
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    handleDown(qrCode){
      companyApi.getQrCode(qrCode).then(res => {
        if (res) {
          let imgData = `data:image/jpeg;base64,${res.replace(
            /[\r\n]/g,
            ""
          )}`;
          this.download.downloadFile('二维码',imgData);
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加客户";
      this.form.isUpdate = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改标签";
      this.form = this.deepClone(row);
      this.form.isUpdate = true;
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.isUpdate) {
            companyApi.companyUpdate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            companyApi.companyAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm("是否确认删除？", "提示").then(res => {
        companyApi.companyDelete(row.deptId).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        });
      });
    },
    chooseDept(row) {
      console.log(row);
      alert(123);
    },
    changeStart(row) {
      companyApi
        .changeStart({ isDelete: row.isDelete, id: row.id })
        .then(res => {
          this.$message.success("执行成功!");
          this.getList();
        })
        .catch(error => {
          console.error(error);
        });
    },
    disableThis(value, deptId) {
      this.loading = true;
      var param = { deptId: deptId, autoCheck: !value };
      companyApi
        .autoCheck(param)
        .then(res => {
          this.loading = false;
          this.getList();
          this.$message({
            message: value == true ? "禁用成功" : "启用成功",
            type: "success"
          });
        })
        .catch(err => {
          this.loading = false;
        });
    },
    setImg(img){
      return img || badImg;
    },
    onchangemd(e){
       // 获取文件
      const file = e.target.files[0];

      // 限制图片类型
      const fileType = file.type;
      const chackImg = fileType==="image/jpeg" || fileType==="image/jpg" || fileType==="image/png"
                    || fileType==="image/JPEG" || fileType==="image/JPG" || fileType==="image/PNG"
      if(!chackImg){
           this.$message.error("照片格式错误！");
           return;
      }
      // 计算文件大小 KB
      const size = Math.floor(file.size / 1024);
      // 显示本地图片
      // this.image = window.URL.createObjectURL(file);

      // 图片转为base64
      var reader = new FileReader();
      reader.readAsDataURL(file); // 一定要传入file格式  
      reader.onload = (e) => {
        this.form.deptLogo=e.target.result;
      };  
    },
    // 触发文件上传
    uploadImg(){
      this.$refs.imgFile.dispatchEvent(new MouseEvent("click"));
    },
  }
};
</script>
<style scoped>
.div-t {
  background: white;
  padding: 10px;
  border-radius: 5px;
  /* border: 1px solid rgb(211, 208, 208); */
}
.div-sch {
  background: white;
  padding: 10px 10px 0px 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}
.switchStyle .el-switch__label {
  position: absolute;
  display: none;
  color: #fff;
}
.el-switch__core {
  background-color: rgba(166, 166, 166, 1);
}
.switchStyle .el-switch__label--left {
  z-index: 9;
  left: 8px;
}
.switchStyle .el-switch__label--right {
  z-index: 9;
  left: -15px;
}
.switchStyle .el-switch__label.is-active {
  display: block;
}
.switchStyle.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 60px !important;
}
</style>
